package com.lgkj.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.lgkj.R;
import com.lgkj.adapter.CityAdapter;
import com.lgkj.bean.CityShopBean;
import com.lgkj.utils.CityJson;
import com.lgkj.utils.CommonConstant;
import com.lgkj.utils.CommonUtils;
import com.lgkj.utils.HttpUtils;
import com.lgkj.utils.PayResult;
import com.lgkj.utils.SharedPreferencesUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/8/10 0010.
 */

public class AdTextActivity extends BaseActivity {
    @BindView(R.id.tv_adress)
    TextView tvAdress;
    @BindView(R.id.lv_shop)
    ListView lvShop;
    @BindView(R.id.et_con)
    EditText etCon;
    String lat = "1", lng = "1";
    int page = 0;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.rb_id)
    CheckBox rbId;
    @BindView(R.id.tv_jisuan)
    TextView tvJisuan;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.et_time)
    EditText etTime;
    @BindView(R.id.tv_time)
    TextView tvTime;
    private CityAdapter adapter;
    public static CityShopBean cityShopBean;
    public static Map<String, Integer> counts;

    @Override
    public int getLayoutId() {
        return R.layout.activity_ad;
    }

    private int position = 0;

    @Override
    public void initView() {
        setTitle("我要打广告");
        lat = SharedPreferencesUtils.getParam(AdTextActivity.this, "lat", "").toString();
        lng = SharedPreferencesUtils.getParam(AdTextActivity.this, "lng", "").toString();
        counts = new HashMap<>();
    }

    @Override
    public void initData() {
        adapter = new CityAdapter(AdTextActivity.this);
        lvShop.setAdapter(adapter);
        adapter.setClick(new CityAdapter.MyClickListener() {
            @Override
            public void clickListener(View v) {
                int index = Integer.parseInt(v.getTag().toString());
                CheckBox checkBox = (CheckBox) v;
                int ische = checkBox.isChecked() ? 1 : 2;
                cityShopBean.getData().get(index).setType(ische);
                forShopName(index, ische);
                Log.i(TAG, "clickListener: " + checkBox.isChecked() + "," + cityShopBean.getData().get(index).getType());
            }
        });
        lvShop.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(AdTextActivity.this, AdCityActivity.class);
                position = i;
                intent.putExtra("city_title", adapter.getItem(i).getName());
                intent.putExtra("city_id", position);
                startActivityForResult(intent, 0);
            }
        });
//        barbershopList();

        etTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int countNum = 0;
                try {
                    countNum = Integer.parseInt(etTime.getText().toString());
                    tvJisuan.setText("价格统计:" + countping() + "*1.8元/天*" + countNum);
                    double price = countping() * (1.8 * countNum);
                    tvPrice.setText(String.format("%.2f", price));
                } catch (Exception e) {
                    Log.e(TAG, "forShopName: " + e.getMessage());
                }
                tvTime.setText(count + "");

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void forShopName(int position, int type) {
        List<CityShopBean.DataBean.BarbershopListBean> data = cityShopBean.getData().get(position).getBarbershop_list();
        for (int i = 0; i < data.size(); i++) {
            if (type == 1) {
                data.get(i).setIscheck(true);
                counts.put(data.get(i).getId(), data.get(i).getProduct_count());
            } else if (type == 2) {
                data.get(i).setIscheck(false);
                counts.remove(data.get(i).getId());
            } else if (type == 0) {
                if (data.get(i).getIscheck()) {
                    counts.put(data.get(i).getId(), data.get(i).getProduct_count());
                } else {
                    counts.remove(data.get(i).getId());
                }
            }
        }
        adapter.notifyDataSetChanged();
        tvCount.setText("已选择" + counts.size() + "家" + "   共" + countping() + "台");
        int countNum = 0;
        try {
            countNum = Integer.parseInt(etTime.getText().toString());
        } catch (Exception e) {
            Log.e(TAG, "forShopName: " + e.getMessage());
        }

        tvJisuan.setText("价格统计:" + countping() + "*1.8元/天*" + countNum);
        double price = countping() * (1.8 * countNum);
        tvPrice.setText(String.format("%.2f", price));
    }

    @OnClick({R.id.ll_adress, R.id.btn_save, R.id.rb_id})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_adress:
                chiooce();
                break;
            case R.id.btn_save:
                save();
                break;
        }
    }


    private void chiooce() {
        AlertDialog.Builder builder = new AlertDialog.Builder(AdTextActivity.this);
        builder.setTitle("选择一个城市");
        builder.setItems(CityJson.getcity(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tvAdress.setText(CityJson.getcity()[which]);
                tvCount.setText("0家");
                barbershopList();
            }
        });
        builder.show();
    }


    private void barbershopList() {
        adapter.setIscheck(false);
        showDiaLog("正在加载中");
        Map<String, String> map = new HashMap<>();
        map.put("access_token", CommonUtils.getToken(AdTextActivity.this));
        map.put("city", tvAdress.getText().toString());
        HttpUtils.postHttp(map, CommonConstant.getDownRegion, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                Gson mGson = new Gson();
                dismissDiaLog();
                if (jsonObject.optInt("code") == 0) {
                    cityShopBean = mGson.fromJson(String.valueOf(jsonObject), CityShopBean.class);
                    if (cityShopBean != null && cityShopBean.getData() != null) {
                        adapter.setDataBeans(cityShopBean.getData());
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void errorHttp(String msg) {
                dismissDiaLog();
            }
        });
    }

    private void save() {
        CommonUtils.showDiaLog(AdTextActivity.this, "正在提交");
        Map<String, String> map = new HashMap<>();
        map.put("access_token", CommonUtils.getToken(AdTextActivity.this));
//        map.put("barbershop", shopIds().toString());
//        map.put("barbershop", "[159, 160, 400]");
        map.put("content", etCon.getText().toString());
        map.put("day", etTime.getText().toString());
        shopIds(map);
        HttpUtils.postHttp(map, CommonConstant.advertAdd, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                toastLong(jsonObject.optString("msg"), 0);
                CommonUtils.dismissDiaLog();
                if (jsonObject.optInt("code") == 0) {
                    zfbPay(jsonObject.optString("data"));
                }
            }

            @Override
            public void errorHttp(String msg) {
                CommonUtils.dismissDiaLog();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        chooce();
        int ss = counts.size();
        adapter.notifyDataSetChanged();
        tvCount.setText("已选择" + ss + "家" + "   共" + countping() + "台,");
    }

    /**
     * 返回商店id
     */
    private void shopIds(Map<String, String> map) {
        List<String> ids = new ArrayList<>();
        for (String key : counts.keySet()) {
            ids.add(key);
        }
        Log.i(TAG, "shopIds: " + ids.toString());
        for (int i = 0; i < ids.size(); i++) {
            map.put("barbershop[" + i + "]", ids.get(i));
        }
    }

    /**
     * 计算台数
     *
     * @return
     */
    private int countping() {
        int count = 0;
        for (Integer value : counts.values()) {
            count = count + value;
        }
        return count;
    }

    /**
     * 计算家
     */
    private void chooce() {
        int count = 0;
        List<CityShopBean.DataBean.BarbershopListBean> data = cityShopBean.getData().get(position).getBarbershop_list();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getIscheck()) {
                count++;
            }
        }
        if (count == 0) {
            cityShopBean.getData().get(position).setType(2);
        } else if (count == data.size()) {
            cityShopBean.getData().get(position).setType(1);
        } else {
            cityShopBean.getData().get(position).setType(0);
        }
        forShopName();
    }

    private void forShopName() {
        int type = 0;
        for (int i = 0; i < cityShopBean.getData().size(); i++) {
            type = cityShopBean.getData().get(i).getType();
            forShopName(i, type);
        }
    }

    private void zfbPay(final String orderInfo) {
        Log.i(TAG, "zfbPay: " + orderInfo);
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(AdTextActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultStatus = payResult.getResultStatus();
                    Log.i(TAG, "handleMessage: " + payResult.toString());
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        toastLong("支付成功", 0);
                    } else {
                        toastLong("支付失败", 0);
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    }
                    break;
            }
        }
    };
}
